package com.atcx.service.impl;

import com.atcx.mapper.AchievementMapper;
import com.atcx.mapper.ClassesMapper;
import com.atcx.mapper.StudentClassMapper;
import com.atcx.mapper.UserMapper;
import com.atcx.mapper.WarningMapper;
import com.atcx.pojo.Achievement;
import com.atcx.pojo.Classes;
import com.atcx.pojo.StudentClass;
import com.atcx.pojo.User;
import com.atcx.pojo.Warning;
import com.atcx.service.AchievementService;
import com.atcx.util.PageResult;
import com.atcx.util.QueryPageBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pangShu
 * @since 2022-03-23
 */
@Service
public class AchievementServiceImpl extends ServiceImpl<AchievementMapper, Achievement> implements AchievementService {

    @Resource
    private WarningMapper warningMapper;
    @Resource
    private StudentClassMapper studentClassMapper;
    @Resource
    private ClassesMapper classesMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AchievementMapper achievementMapper;
    @Override
    public int addAchievement(Achievement achievement) {
        //设置学生名字
        User user = userMapper.selectById(achievement.getUserid());
        //查询班级信息
        QueryWrapper<StudentClass> wrapper = new QueryWrapper();
        wrapper.eq("userId",user.getUserid());
        StudentClass studentClass = studentClassMapper.selectOne(wrapper);
        achievement.setClassid(studentClass.getClassid());
        achievement.setName(user.getName());
        //首先计算总成绩
        Achievement compute = compute(achievement);
        int insert = achievementMapper.insert(compute);
        //最后计算排名
        getRanking();
        return insert;
    }

    @Override
    public int deleteAchievement(int id) {
        int i = achievementMapper.deleteById(id);
        getRanking();
        return i;
    }

    @Override
    public int updateAchievement(Achievement achievement) {
        Achievement compute = compute(achievement);
        QueryWrapper<Achievement> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",achievement.getUserid());
        int i = achievementMapper.update(achievement,wrapper);
        getRanking();
        return i;
    }

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        Page<Achievement> page = new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        QueryWrapper<Achievement> queryWrapper = new QueryWrapper<>();
        if (queryPageBean.getQueryString() != null&&queryPageBean.getQueryString().trim().length()!=0){
            //有查询条件就添加查询条件
            String trim = queryPageBean.getQueryString().trim();
            queryWrapper.eq("name",trim).or().eq("classId",trim);
        }
        queryWrapper.orderByDesc("total");//按照总成绩降序
        Page<Achievement> achievementPage = achievementMapper.selectPage(page, queryWrapper);
        PageResult pageResult = new PageResult(achievementPage.getTotal(), achievementPage.getRecords());
        return pageResult;
    }
    /**
     * @Author:pangshu
     * @Description: 成绩导出
     * @Date:9:40 2022/3/25
     * @Param:
     * @return: java.lang.Boolean
     **/
    @Override
    public Boolean outputSheet() {
        List<Achievement> achievements = achievementMapper.selectList(new QueryWrapper<Achievement>());
        Boolean flag = false;
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("学生成绩");
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("准考证号");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("学号");
        row.createCell(3).setCellValue("高等数学");
        row.createCell(4).setCellValue("大学英语");
        row.createCell(5).setCellValue("C语言");
        row.createCell(6).setCellValue("计算机文化基础");
        row.createCell(7).setCellValue("Web前端开发");
        row.createCell(8).setCellValue("总成绩");
        row.createCell(9).setCellValue("总排名");
        row.createCell(10).setCellValue("平均成绩");
        row.createCell(11).setCellValue("未及格科目数");
//        for (int i = 0; i < achievements.size(); i++) {
//
//        }
        int i = 1;
        for (Achievement achievement : achievements) {
            XSSFRow xssfRow = sheet.createRow(i);
            xssfRow.createCell(0).setCellValue(achievement.getId());
            xssfRow.createCell(1).setCellValue(achievement.getName());
            xssfRow.createCell(2).setCellValue(achievement.getUserid());
            xssfRow.createCell(3).setCellValue(achievement.getMath().toString());
            xssfRow.createCell(4).setCellValue(achievement.getEnglish().toString());
            xssfRow.createCell(5).setCellValue(achievement.getClanguage().toString());
            xssfRow.createCell(6).setCellValue(achievement.getComputer().toString());
            xssfRow.createCell(7).setCellValue(achievement.getWeb().toString());
            xssfRow.createCell(8).setCellValue(achievement.getTotal().toString());
            xssfRow.createCell(9).setCellValue(achievement.getRanking());
            xssfRow.createCell(10).setCellValue(achievement.getAverage().toString());
            xssfRow.createCell(11).setCellValue(achievement.getFailcount());

            i++;
        }
        File file = new File("D:/images/学生成绩.xlsx");
        try {
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            workbook.write(fileOutputStream);
            fileOutputStream.flush();

            fileOutputStream.close();
            workbook.close();
            flag = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }
    //成绩报表
    @Override
    public Map<String, Object> getOneScore(int userId) {
        Achievement achievement = achievementMapper.selectOne(new QueryWrapper<Achievement>().eq("userId", userId));
        Map<String, Object> map = getMap(achievement);
        return map;
    }
    //封装报表数据
    public Map<String,Object> getMap(Achievement selectOne){
        Map<String,Object> map = new HashMap<>();
        List<String> majors = new ArrayList<>();
        List<BigDecimal> scores = new ArrayList<>();
        majors.add("高等数学");
        majors.add("大学英语");
        majors.add("C语言");
        majors.add("计算机文化基础");
        majors.add("web前端开发");
        scores.add(selectOne.getMath());
        scores.add(selectOne.getEnglish());
        scores.add(selectOne.getClanguage());
        scores.add(selectOne.getComputer());
        scores.add(selectOne.getWeb());
        map.put("majors",majors);
        map.put("scores",scores);
        return map;
    }

    //计算平均成绩，总成绩
    public Achievement compute(Achievement achievement){
        //计算总成绩

        BigDecimal total = new BigDecimal(0);
        BigDecimal one =total.add(achievement.getMath()).add(achievement.getEnglish()).add(achievement.getClanguage()).add(achievement.getComputer()).add(achievement.getWeb());
        achievement.setTotal(one);
        //计算平均成绩
        achievement.setAverage(one.divide(new BigDecimal("5")));
        BigDecimal flag = new BigDecimal("60");
        //判断不及格
        Integer failCount = 0;
        String fail = "";
        if (achievement.getMath().compareTo(flag)<0){
            fail = fail.concat("高等数学,");
            failCount = failCount + 1;
        }
        if (achievement.getEnglish().compareTo(flag)<0){
            fail = fail.concat("大学英语,");
            failCount = failCount + 1;
        }
        if (achievement.getClanguage().compareTo(flag)<0){
            fail = fail.concat("c语言,");
            failCount = failCount + 1;
        }
        if (achievement.getComputer().compareTo(flag)<0){
            fail = fail.concat("计算机文化基础,");
            failCount = failCount + 1;
        }
        if (achievement.getWeb().compareTo(flag)<0){
            fail = fail.concat("web前端开发");
            failCount = failCount + 1;
        }
        achievement.setFailcount(failCount);
        achievement.setFailSubject(fail);
        //添加学情警告szdt
        if (failCount>0){
            Warning warning = new Warning();
            warning.setFailcount(failCount);
            warning.setExamtime(LocalDateTime.now());
            QueryWrapper<StudentClass> wrapper = new QueryWrapper<>();
            wrapper.eq("userId",achievement.getUserid());
            StudentClass studentClass = studentClassMapper.selectOne(wrapper);
            Classes classes = classesMapper.selectOne(new QueryWrapper<Classes>().eq("classId", studentClass.getClassid()));
            warning.setTeacher(classes.getTeacher());
            warning.setClassname(classes.getClassname());
            warning.setName(achievement.getName());
            warning.setFailSubject(fail);
            int insert = warningMapper.insert(warning);
        }
        return achievement;
    }
    //计算总排名git
    public void getRanking(){
        QueryWrapper<Achievement> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("total");
        List<Achievement> achievements = achievementMapper.selectList(wrapper);
        for (int i = 0; i <achievements.size() ; i++) {
            int j = i+1;
            achievements.get(i).setRanking(j);
            achievementMapper.updateById(achievements.get(i));
        }
    }
}
